package com.sqllog.admin.sql.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageInfo;
import com.sqllog.admin.auth.domain.response.Result;
import com.sqllog.admin.auth.domain.response.module.ResultTable;
import com.sqllog.admin.framework.controller.ResultController;
import com.sqllog.admin.framework.domain.request.PageDomain;
import com.sqllog.admin.sql.entity.LogDatabaseManager;
import com.sqllog.admin.sql.service.LogDatabaseManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 日志数据库
 *
 * @author chennengcheng
 * @date 2022-01-23 15:32
 * @remark
 */

@RestController
@RequestMapping("/logDatabase/")
public class LogDatabaseManagerController  extends ResultController {

    /**
     * Describe: 基础路径
     */
    private static String MODULE_PATH = "logDatabase/";

    @Autowired
    private LogDatabaseManagerService logDatabaseManagerService;


    @GetMapping("main")
    public ModelAndView main(ModelAndView modelAndView) {
        return jumpPage(MODULE_PATH + "main");
    }

    @GetMapping("data")
    public ResultTable data(PageDomain pageDomain, String collectionName) {
        PageInfo<LogDatabaseManager> logDatabaseManagerPageInfo = logDatabaseManagerService.selectByQueryName(pageDomain, collectionName);
        return pageTable(logDatabaseManagerPageInfo.getList(), logDatabaseManagerPageInfo.getTotal());
    }

    @GetMapping("getAllByQueryName")
    public Result<List<String>> getAllByQueryName(String name) {
        List<LogDatabaseManager> logDatabaseManagers = logDatabaseManagerService.selectByQueryName(name);
        List<String> datas = logDatabaseManagers.stream().map(LogDatabaseManager::getQueryName).collect(Collectors.toList());
        return Result.success(datas);
    }

    @DeleteMapping("remove/{id}")
    public Result remove(@PathVariable String id) {
        int i = logDatabaseManagerService.deleteById(id);
        return decide(i > 0);
    }

    @DeleteMapping("batchRemove/{ids}")
    public Result batchRemove(@PathVariable String ids) {
        ArrayList<String> idList = CollectionUtil.newArrayList(StrUtil.split(ids, ","));
        for (String id : idList) {
            logDatabaseManagerService.deleteById(id);
        }

        return decide(true);
    }
}
